<template>
  <p>
    <a-space>
      <!-- 车次选择下拉框-->
      <train-select v-model="queryTrainCode" width="200px"/>
      <a-button type="primary" @click="handleQuery()">查找</a-button>
      <a-button type="primary" @click="onAdd">新增</a-button>
    </a-space>
  </p>
  <!--表格-->
  <a-table :dataSource="trainStations"
           :columns="columns"
           :pagination="pagination"
           @change="handleTableChange"
           :loading="loading">
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'operation'">
        <a-space>
          <a-popconfirm
              title="删除后不可恢复，确认删除?"
              @confirm="onDelete(record)"
              ok-text="确认" cancel-text="取消">
            <a style="color: red">删除</a>
          </a-popconfirm>
          <a @click="onEdit(record)">编辑</a>
        </a-space>
      </template>
      <template v-else-if="column.dataIndex === 'inTime'">
        {{ record.inTime == null ? '--' : record.inTime }}
      </template>
      <template v-else-if="column.dataIndex === 'outTime'">
        {{ record.outTime == null ? '--' : record.outTime }}
      </template>
      <template v-else-if="column.dataIndex === 'stopTime'">
        {{ record.stopTime == null ? '--' : record.stopTime }}
      </template>
    </template>
  </a-table>
  <!--添加表单-->
  <a-modal v-model:visible="visible" title="停靠站" @ok="handleOk"
           ok-text="确认" cancel-text="取消">
    <a-form :model="trainStation" :label-col="{span: 5}" :wrapper-col="{ span: 20 }">
      <a-form-item label="车次编号">
        <!-- 车次选择下拉框-->
        <train-select v-model="trainStation.trainCode"/>
      </a-form-item>
      <a-form-item label="站序">
        <a-input v-model:value="trainStation.index" />
      </a-form-item>
      <a-form-item label="站名">
        <!-- 车站选择下拉框-->
        <station-select v-model="trainStation.name"/>
      </a-form-item>
      <a-form-item label="站名拼音">
        <span class="station_py">{{trainStation.namePinyin}}</span>
      </a-form-item>
      <a-form-item label="进站时间">
        <a-time-picker v-model:value="trainStation.inTime"
                       format="HH:mm"
                       valueFormat="HH:mm"
                       placeholder="请选择时间"/>
      </a-form-item>
      <a-form-item label="出站时间">
        <a-time-picker v-model:value="trainStation.outTime"
                       format="HH:mm"
                       valueFormat="HH:mm"
                       placeholder="请选择时间"/>
      </a-form-item>
      <a-form-item label="停站时长">
        <a-time-picker v-model:value="trainStation.stopTime"
                       format="HH:mm"
                       valueFormat="HH:mm"
                       placeholder="请选择时间"
                       disabled/>
      </a-form-item>
      <a-form-item label="里程（公里）">
        <a-input v-model:value="trainStation.km" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import {onMounted, ref, watch} from 'vue';
import request from "@/utils/request";
import {notification} from 'ant-design-vue'
import {pinyin} from "pinyin-pro";
import TrainSelect from "@/components/TrainSelect.vue";
import StationSelect from "@/components/StationSelect.vue";
import dayjs from 'dayjs'

// 添加火车停靠站的属性
let trainStation = ref({
  id: undefined,
  trainCode: undefined,
  index: undefined,
  name: undefined,
  namePinyin: undefined,
  inTime: undefined,
  outTime: undefined,
  stopTime: undefined,
  km: undefined
});
// 表格数据
const trainStations = ref([]);
// 分页的三个属性名是固定的
const pagination = ref({
  position: ['bottomCenter'],
  total: 0,
  current: 1,
  pageSize: 8,
  showSizeChanger: true,
  pageSizeOptions: ['8', '15', '20']
});
// 表格展示列
const columns = [
  {
    title: '车次编号',
    dataIndex: 'trainCode',
    key: 'trainCode',
  },
  {
    title: '站序',
    dataIndex: 'index',
    key: 'index',
  },
  {
    title: '站名',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '站名拼音',
    dataIndex: 'namePinyin',
    key: 'namePinyin',
  },
  {
    title: '进站时间',
    dataIndex: 'inTime',
    key: 'inTime',
  },
  {
    title: '出站时间',
    dataIndex: 'outTime',
    key: 'outTime',
  },
  {
    title: '停站时长',
    dataIndex: 'stopTime',
    key: 'stopTime',
  },
  {
    title: '里程（公里）',
    dataIndex: 'km',
    key: 'km',
  },
  {
    title: '操作',
    dataIndex: 'operation'
  }
];

// 新增按钮隐藏属性
const visible = ref(false);
// 点击添加按钮，表单显示
const onAdd = () => {
  trainStation.value = {};
  visible.value = true;
};

// 监视站名，转换拼音和首字母
watch(() => trainStation.value.name, ()=>{
  trainStation.value.namePinyin = Tool.isNotEmpty(trainStation.value.name)
    ? pinyin(trainStation.value.name, { toneType: 'none'}).replaceAll(" ", "")
    : trainStation.value.namePinyin = undefined;
}, {immediate: true});

// 编辑火车停靠站
const onEdit = (record) => {
  trainStation.value = window.Tool.copy(record);
  visible.value = true;
};

// 删除火车停靠站
const onDelete = (record) => {
  request.delete(`/business/admin/train-station/delete/${record.id}`)
    .then((result) => {
      if (result.status) {
        notification.success({description: result.message});
        handleQuery({
          pageNum: pagination.value.current,
          pageSize: pagination.value.pageSize,
        });
      } else {
        notification.error({description: result.message});
      }
  });
};

// 自动计算停车时长
watch(() => trainStation.value.inTime, () => {
  let diff = dayjs(trainStation.value.outTime, 'HH:mm').diff(dayjs(trainStation.value.inTime, 'HH:mm'), 'seconds');
  trainStation.value.stopTime = dayjs('00:00', 'HH:mm').second(diff).format('HH:mm');
  if (trainStation.value.stopTime === "Invalid Date") trainStation.value.stopTime = null
}, {immediate: true});
watch(() => trainStation.value.outTime, () => {
  let diff = dayjs(trainStation.value.outTime, 'HH:mm').diff(dayjs(trainStation.value.inTime, 'HH:mm'), 'seconds');
  trainStation.value.stopTime = dayjs('00:00', 'HH:mm').second(diff).format('HH:mm');
  if (trainStation.value.stopTime === "Invalid Date") trainStation.value.stopTime = null
}, {immediate: true});

// 请求 -- 保存火车停靠站
const handleOk = () => {
  request.post("/business/admin/train-station/save", {
    ...trainStation.value,
    inTime: trainStation.value.inTime != null ? `${trainStation.value.inTime}:00` : null,
    outTime: trainStation.value.outTime != null ? `${trainStation.value.outTime}:00` : null,
    stopTime: trainStation.value.stopTime != null ? `${trainStation.value.stopTime}:00` : null
  })
    .then((result) => {
      if (result.status) {
      notification.success({description: result.message});
      visible.value = false;
      handleQuery({
        pageNum: pagination.value.current,
        pageSize: pagination.value.pageSize
      });
    } else {
      notification.error({description: result.message});
    }
  });
};

// 表格加载
let loading = ref(false);
// 查询车次编号
let queryTrainCode = ref(null);
// 请求 -- 查询火车停靠站
const handleQuery = (param) => {
  // 如果无参，则查询当前页
  if (!param) {
    param = {
      pageNum: pagination.value.current,
      pageSize: pagination.value.pageSize
    }
  }
  loading.value = true;
  request.get("/business/admin/train-station/list", {
    params: {
      pageNum: param.pageNum,
      pageSize: param.pageSize,
      trainCode: queryTrainCode.value
    }
  }).then((result) => {
    loading.value = false;
    if (result.status) {
      trainStations.value = result.content.records;
      // 设置分页控件的值
      pagination.value.current = param.pageNum;
      pagination.value.total = result.content.total;
    } else {
      notification.error({description: result.message});
    }
  });
};

// 表格换页，调用请求
const handleTableChange = (page) => {
  pagination.value = page
  handleQuery({
    pageNum: page.current,
    pageSize: page.pageSize,
  });
};

onMounted(() => {
  handleQuery({
    pageNum: 1,
    pageSize: pagination.value.pageSize
  });
});
</script>
